package com.zhaowb.springcloud.gate.config;

import com.zhaowb.springcloud.gate.jwt.JwtAuthenticationTokenFilter;
import com.zhaowb.springcloud.gate.service.GateUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Created with IDEA
 * Web Security 配置
 *
 * @author zhaowb
 * @date 2018/11/9 21:13
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private GateUserDetailsService detailsService;

    @Value("${gate.ignore.startWith}")
    private String startWith;

    @Bean
    public JwtAuthenticationTokenFilter authenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login").defaultSuccessUrl("/admin/index").permitAll().and()
                .logout().logoutUrl("/login").invalidateHttpSession(true).and().authorizeRequests()
                // 放开"/api/**",通过oauth2.0来鉴权
                .antMatchers("/**/*.css", "/img/**", "/**/*.js", "/api/**", "/*/api/**")
                .permitAll().and().authorizeRequests().antMatchers("/**").authenticated();

        http.csrf().disable();
        http.headers().frameOptions().disable();
        http.httpBasic();

        // 添加jwt filter
        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        // 禁用缓存
        http.headers().cacheControl();
        http.headers().contentTypeOptions().disable();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(detailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}